<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\GoodsBrowse;
use App\Models\User;


class GenerateUserGoodsBrowse implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $users;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(User $user , $ttl)
    {
        $this->users = $user;

        // 设置延迟的时间，delay() 方法的参数代表多少秒之后执行
        $this->delay($ttl);
        //
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $user = $this->users; // 用户对象
        foreach ($user->goods as $gv) {
            $GoodsBrowse = factory(GoodsBrowse::class)->times($user->shop->count())
                ->make()->each(function($query , $index) use ($user , $gv){ // 生成用户有多少分销的集合数据
                    $query->user_id     = $user->id; // 每个用户的ID
                    $query->goods_id    = $gv->id; // 每个商品的ID
                    $query->shop_id     = $user->shop[$index]->id;// 每个店铺的ID
                    $query->pagevies    = 0; // 浏览量
                    $query->order_num   = 0; // 订单量
                    $query->deal_num    = 0; // 成交量
                    $query->show_num    = 0; // 展现量
                    $query->created_at  = now(); // 时间
                    $query->updated_at  = now(); // 时间
                });
            GoodsBrowse::insert($GoodsBrowse->toArray());// 插入浏览表数据
        }
    }
}
